/*
 * @(#)ImageByOwfsAction.java $version 2011. 10. 14
 * 
 * Copyright 2011 NHN Corp. All rights Reserved.
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.hangame.mbl.action.feed;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hangame.mbl.action.SmartPortalAction;
import com.hangame.mbl.bo.feed.ImageByOwfsBO;
import com.nhncorp.lucy.file.upload.FileItem;
import com.nhncorp.lucy.security.permission.Permissions;
import com.nhncorp.lucy.web.metadata.Inject;

// TODO: Auto-generated Javadoc
/**
 * The Class ImageByOwfsAction.
 *
 * @author NHN
 */
public class ImageByOwfsAction extends SmartPortalAction {
	
	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -8004781107472000697L;
	
	/** The log. */
	private static Log log = LogFactory.getLog(ImageByOwfsAction.class);

	/** The image by owfs bo. */
	protected ImageByOwfsBO imageByOwfsBO = null;

	/**
	 * Sets the image by owfs bo.
	 * 
	 * @param imageByOwfsBO the new image by owfs bo
	 */
	@Inject(beanId = "imageByOwfsBO")
	public void setImageByOwfsBO(ImageByOwfsBO imageByOwfsBO) {
		this.imageByOwfsBO = imageByOwfsBO;
	}

	/** The file items map. */
	protected Map<String, FileItem[]> fileItemsMap;

	/** The Constant EXTENTIONS. */
	public static final List<String> EXTENTIONS = Arrays.asList(new String[] {"gif", "jpg", "bmp", "png", "jpeg", "GIF", "JPG", "BMP", "PNG", "JPEG"});

	/* (non-Javadoc)
	 * @see com.hangame.mbl.action.SmartPortalAction#execute()
	 */
	@Override
	public String execute() throws Exception {

		return NONE;
	}

	/**
	 * Upload file.
	 *
	 * @return the string
	 * @throws Exception the exception
	 */
	@Permissions(required = "login")
	public String uploadFile() throws Exception {
//		int gameNo = NumberUtils.toInt(params.getString("gameNo"), 0); // 전체게임 일때. gameNo = 0으로 처리.
//		String isMyFeed = StringUtils.defaultIfEmpty(params.getString("isMyFeed"), "N");
//		int page = NumberUtils.toInt(params.getString("page"), 1);
//		String beforeSpace = StringUtils.defaultIfEmpty(params.getString("beforeSpace"), "");

		String result = "SUCCESS";
		String fileUploadURL = ""; // User의 결과 fileUploadURL

		LOG.debug("######## OWFS upload start ########");
		LOG.debug("######## register game source params " + params);

		try {
			// 1. 인터셉터로 세팅된 파일 정보 가져오기
			Map<String, FileItem[]> fileItemMap = getFileItemsMap();
			LOG.debug("######## fileItemMap : " + fileItemMap);

			// 2. 각각의 파일 업로드
			for (String key : fileItemMap.keySet()) {

				FileItem[] fileItem = fileItemMap.get(key);

				if (fileItem != null) {
					File souceFile = fileItem[0].getFile(); // FILE
					String fileName = fileItem[0].getFilename(); // FILE name

					// 파일 크기 검사 5MB.
					if (fileItem[0].getSize() > 5242880L) { // 5MB
						log.debug("upload File Too Big!");
						result = "TOO_BIG";
						break;
					}

					// 확장자 검사.
					String extension = StringUtils.lowerCase(FilenameUtils.getExtension(fileName));

					if (extension == null) {
						log.debug("extension empty!");
						result = "EXT_ERR";
						break;
					}
					if (EXTENTIONS.contains(extension) == false) {
						log.debug("extension type err!");
						result = "EXT_ERR";
						break;
					}

					// ContentType image 인지 검사.
					String[] getContentType = StringUtils.split(fileItem[0].getContentType(), "/");

					if (getContentType != null && getContentType.length > 0) {
						if (!"image".equalsIgnoreCase(getContentType[0])) {
							log.debug("getContentType ERROR!");
							result = "TYPE_ERR";
							break;
						}
					} else {
						result = "TYPE_ERR";
						break;
					}

					LOG.debug("######## OWFS souceFile : " + fileName);
					String owfsResult = imageByOwfsBO.uploadOwfsFile(souceFile, extension); // Owfs File upload

					if (owfsResult.equalsIgnoreCase("OWFS_ERR")) { // OWFS 실패
						LOG.error("######## OWFS upload ERROR!!");
						fileUploadURL = "";
						result = "OWFS_ERR";
						break;
					} else { // OWFS 성공시,
						fileUploadURL = owfsResult;
					}
				}
			}
		} catch (Exception e) {
			LOG.error("######## upload Exception : " + e);
			result = e.toString();
		} finally {
			LOG.debug("######## OWFS upload end ########");
		}

		setAttribute("result", result);
		setAttribute("fileUploadURL", fileUploadURL);

		log.debug("result===" + result);
		log.debug("fileUploadURL===" + fileUploadURL);

		return SUCCESS;

	}

}
